<template>
  <div class="full" v-loading="loading" element-loading-text="用例拼命运行中，请稍等..."
       element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.6)">
    <div>
      <!--面包屑-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>接口测试</el-breadcrumb-item>
        <el-breadcrumb-item>接口管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!--卡片-->
      <el-card class="box-card">
        <el-row :gutter="20">
          <!--搜索框-->
          <el-col :span="6">
            <el-input placeholder="请输入接口名称" v-model="queryParams.name" clearable @clear="getInterfaceList" @keyup.enter.native="getInterfaceList">
              <el-button slot="append" icon="el-icon-search" @click="getInterfaceList" class="search"></el-button>
            </el-input>
          </el-col>
          <!--创建按钮-->
          <el-col :span="4">
            <el-button type="primary" @click="openAddInterfaceDialog" plain>创建接口</el-button>
          </el-col>
        </el-row>
        <!--表格-->
        <el-table :data="interfaceList" :cell-style="cellStyle" border stripe>
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column label="接口名称" prop="name"></el-table-column>
          <el-table-column label="所属项目" prop="project"></el-table-column>
          <el-table-column label="创建时间" prop="create_time"></el-table-column>
          <el-table-column label="操作" min-width="77px">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="openRunInterfaceDialog(scope.row)" plain>运 行</el-button>
              <el-button type="warning" size="mini" @click="openEditInterfaceDialog(scope.row)" plain>编 辑</el-button>
              <el-button type="danger" size="mini" @click="deleteThisInterface(scope.row.id)" plain>删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.p"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="queryParams.s"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
      <!--新建接口对话框-->
      <el-dialog title="创建接口" :visible.sync="addInterfaceDialogVisible" width="40%" :append-to-body="true"
                 :close-on-click-modal="false" :close-on-press-escape="false" @close="addDialogClose">
        <!--接口表单-->
        <el-form :model="addInterfaceForm" status-icon :rules="addInterfaceRule" ref="addInterfaceRef" label-width="90px">
          <el-form-item label="所属项目" prop="project_id">
            <el-select v-model="addInterfaceForm.project_id" placeholder="请选择所属项目">
              <el-option
                v-for="project in projectAndInterfaceNames"
                :key="project.id"
                :label="project.name"
                :value="project.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="接口名称" prop="name">
            <el-input v-model="addInterfaceForm.name" placeholder="请输入接口名称"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addInterfaceDialogClose">取 消</el-button>
          <el-button type="primary" @click="addInterface">确 定</el-button>
        </span>
      </el-dialog>
      <!--编辑接口对话框-->
      <el-dialog title="编辑接口" :visible.sync="editInterfaceDialogVisible" width="40%" :append-to-body="true"
                 :close-on-click-modal="false" :close-on-press-escape="false" @close="editDialogClose">
        <!--接口表单-->
        <el-form :model="editInterfaceForm" status-icon :rules="editInterfaceRule" ref="editInterfaceRef" label-width="90px">
          <el-form-item label="所属项目" prop="project_id">
            <el-select v-model="editInterfaceForm.project_id" placeholder="请选择所属项目">
              <el-option
                v-for="project in projectAndInterfaceNames"
                :key="project.id"
                :label="project.name"
                :value="project.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="接口名称" prop="name">
            <el-input v-model="editInterfaceForm.name" placeholder="请输入接口名称"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editInterfaceDialogClose">取 消</el-button>
          <el-button type="primary" @click="editThisInterface">确 定</el-button>
        </span>
      </el-dialog>
      <!--运行接口对话框-->
      <el-dialog title="运行接口" :visible.sync="runInterfaceDialogVisible" width="20%" :append-to-body="true"
                 :close-on-click-modal="false" :close-on-press-escape="false" @close="runDialogClose">
        <el-form :model="runInterfaceForm" status-icon :rules="runInterfaceRule" ref="runInterfaceRef" label-width="90px">
          <el-form-item label="运行环境" prop="env_id">
            <el-select v-model="runInterfaceForm.env_id" placeholder="请选择运行环境">
              <el-option
                v-for="env in environmentList"
                :key="env.id"
                :label="env.name"
                :value="env.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="runInterfaceDialogClose">取 消</el-button>
        <el-button type="primary" @click="runThisInterface">开 始</el-button>
      </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getInterfaces,
  getProjectAndInterfaceNames,
  getEnvironmentNames,
  createInterface,
  editInterface,
  deleteInterface,
  runInterface
} from '../../api/api'

export default {
  created () {
    this.getInterfaceList()
    this.getProjectAndInterfaceNameList()
  },
  data () {
    return {
      interfaceList: [],
      queryParams: {
        p: 1,
        s: 10,
        name: ''
      },
      total: 0,
      addInterfaceDialogVisible: false,
      addInterfaceForm: {
        name: '',
        project_id: ''
      },
      editInterfaceDialogVisible: false,
      editInterfaceForm: {},
      projectAndInterfaceNames: [],
      interfaceId: '',
      addInterfaceRule: {
        project_id: [
          { required: true, message: '所属项目不能为空！', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '接口名称不能为空！', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符！', trigger: 'blur' }
        ]
      },
      editInterfaceRule: {
        project_id: [
          { required: true, message: '所属项目不能为空！', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '接口名称不能为空！', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符！', trigger: 'blur' }
        ]
      },
      // 运行
      runInterfaceDialogVisible: false,
      runInterfaceForm: {
        env_id: ''
      },
      runInterfaceRule: {
        env_id: [
          { required: true, message: '运行环境不能为空！', trigger: 'blur' }
        ]
      },
      loading: false,
      environmentList: [],
      runInterfaceId: ''
    }
  },
  methods: {
    // 获取环境名称列表
    getEnvironmentNameList () {
      getEnvironmentNames()
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取环境名称列表失败！')
          this.environmentList = response.data.data
        })
    },
    // 打开运行接口对话框
    openRunInterfaceDialog (interfaceInfo) {
      this.runInterfaceId = interfaceInfo.id
      this.getEnvironmentNameList()
      this.runInterfaceDialogVisible = true
    },
    // 运行接口
    runThisInterface () {
      this.$refs.runInterfaceRef.validate(valid => {
        if (!valid) return
        this.loading = true
        this.runInterfaceDialogVisible = false
        runInterface(this.runInterfaceId, this.runInterfaceForm)
          .then(response => {
            if (response.data.code !== 0) {
              this.loading = false
              return this.$message.error(response.data.message.run)
            }
            this.loading = false
            this.$message.success(response.data.message.run)
            this.runInterfaceId = ''
            this.runInterfaceForm = { env_id: '' }
          })
      })
      this.getInterfaceList()
    },
    // 运行对话框关闭
    runDialogClose () {
      this.$refs.runInterfaceRef.resetFields()
      this.environmentList = []
    },
    // 运行接口对话框关闭
    runInterfaceDialogClose () {
      this.runInterfaceDialogVisible = false
      this.runDialogClose()
      this.runInterfaceId = ''
      this.runInterfaceForm = {
        env_id: ''
      }
    },
    // 获取接口列表
    getInterfaceList () {
      if (this.queryParams.name !== this.tmpName) {
        this.tmpName = this.queryParams.name
        this.queryParams.p = 1
      }
      getInterfaces(this.queryParams)
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取接口列表失败！')
          this.interfaceList = response.data.data.results
          this.total = response.data.data.count
        })
    },
    // 获取项目名称列表
    getProjectAndInterfaceNameList () {
      getProjectAndInterfaceNames()
        .then(response => {
          if (response.data.code !== 0) return this.$message.error('获取项目名称列表失败！')
          this.projectAndInterfaceNames = response.data.data
        })
    },
    // 打开创建接口的对话框
    openAddInterfaceDialog () {
      this.addInterfaceDialogVisible = true
    },
    // 创建对话框关闭
    addDialogClose () {
      this.$refs.addInterfaceRef.resetFields()
      this.addInterfaceForm = {
        name: '',
        project_id: ''
      }
    },
    // 关闭创建接口的对话框
    addInterfaceDialogClose () {
      this.addInterfaceDialogVisible = false
      this.addDialogClose()
    },
    // 创建接口
    addInterface () {
      this.$refs.addInterfaceRef.validate(valid => {
        if (!valid) return
        createInterface(this.addInterfaceForm)
          .then(response => {
            if (response.data.code !== 0) return this.$message.error('创建接口失败！')
            this.$message.success('创建接口成功！')
            this.addInterfaceDialogClose()
            this.getInterfaceList()
          })
      })
    },
    // 打开编辑接口的对话框
    openEditInterfaceDialog (interfaceInfo) {
      this.editInterfaceForm = { ...interfaceInfo }
      this.interfaceId = this.editInterfaceForm.id
      delete this.editInterfaceForm.id
      delete this.editInterfaceForm.project
      delete this.editInterfaceForm.create_time
      this.editInterfaceDialogVisible = true
    },
    // 编辑对话框关闭
    editDialogClose () {
      this.$refs.editInterfaceRef.resetFields()
    },
    // 关闭编辑接口的对话框
    editInterfaceDialogClose () {
      this.editInterfaceDialogVisible = false
      this.editDialogClose()
    },
    // 编辑接口
    editThisInterface () {
      this.$refs.editInterfaceRef.validate(valid => {
        if (!valid) return
        editInterface(this.interfaceId, this.editInterfaceForm)
          .then(response => {
            if (response.data.code !== 0) return this.$message.error('编辑接口失败！')
            this.$message.success('编辑接口成功！')
            this.editInterfaceDialogClose()
            this.getInterfaceList()
          })
      })
    },
    // 删除这个接口
    deleteThisInterface (interfaceId) {
      this.$confirm('此操作将永久删除该接口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteInterface(interfaceId).then(response => {
          if (response.data.code !== 0) return this.$message.error('删除接口失败！')
          this.$message.success('删除接口成功！')
          this.total -= 1
          if (this.total === (this.queryParams.p - 1) * this.queryParams.s && this.total !== 0) {
            this.queryParams.p -= 1
          }
          this.getInterfaceList()
        })
      }).catch(err => err)
    },
    // 监听size变化
    handleSizeChange (newSize) {
      this.queryParams.s = newSize
      this.getInterfaceList()
    },
    // 监听页码变化
    handleCurrentChange (newPage) {
      this.queryParams.p = newPage
      this.getInterfaceList()
    },
    // 表格样式
    cellStyle (data) {
      if (data.column.label === '接口名称') {
        return 'color: #409EFF'
      }
    }
  }
}
</script>

<style lang="less" scoped>
  /deep/ .el-dialog__body {
    padding: 20px 35px 10px 20px;
  }
</style>
